package com.lalosoft.misgastos.activities;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.lalosoft.misgastos.R;
import com.lalosoft.misgastos.config.Constants;
import com.lalosoft.misgastos.config.GastosManager;
import com.lalosoft.misgastos.config.Utils;
import com.lalosoft.misgastos.domain.Item;
import com.lalosoft.misgastos.receiver.GastosReceiver;
import com.lalosoft.misgastos.service.GastosTarjetaService;
import com.lalosoft.misgastos.service.impl.GastosTarjetaServiceImpl;

public class AddItemActivity extends Activity {
	
	private EditText detalle;
	private EditText valorCuota;
	private EditText cantidadCuota;
	private EditText fechaCompra;
	private Button agregar;
	private Context context = AddItemActivity.this;

	private static String TAG = "AddItemActivity";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_item);
		detalle = (EditText) findViewById(R.id.add_item_detalle);
		valorCuota = (EditText) findViewById(R.id.add_item_valor);
		cantidadCuota = (EditText) findViewById(R.id.add_item_cantidad);
		fechaCompra = (EditText) findViewById(R.id.add_item_fecha);
		agregar = (Button) findViewById(R.id.add_item_button);
		
		fill();//borrar
		
		agregar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final Item item = new Item();
				item.setCantidadCuotas(Integer.valueOf(cantidadCuota.getText().toString()));
				item.setDetalle(detalle.getText().toString());
				item.setFechaCompra(fechaCompra.getText().toString());
				item.setValorCuota(Double.valueOf(valorCuota.getText().toString()));
				item.setCuotasRestantes(Integer.valueOf(cantidadCuota.getText().toString()));
				if(Utils.checkNetwork(getApplicationContext()).equals("OK")){
					addItem(item);
				} else {
					Toast.makeText(getApplicationContext(), "No se sincronizo con la web!", Toast.LENGTH_SHORT).show();
				}
			}
		});
	}
	
	private void addItem(final Item item){
		final ProgressDialog dialog;
		dialog = new ProgressDialog(context);
		dialog.setMessage("Espere...");
		dialog.show();
		final Handler h = new Handler();
		Thread t = new Thread(){
			public void run() {
				GastosTarjetaService service = new GastosTarjetaServiceImpl();
				GastosManager manager = GastosManager.getInstance(context);
				String userToken = GastosManager.getInstance(context).getCurrentAccount().getUserToken();
				String itemId = "";
				try {
					itemId = service.saveItem(userToken, item);
					item.setIdDB(itemId);
					manager.saveItem(item);
//					Toast.makeText(context, "Item guardado!!", Toast.LENGTH_SHORT).show();
					Log.d("AddItemActivity", "Se ha agregado un nuevo item: " + item.getDetalle());
				} catch (Exception e) {
					Log.e("AddItemActivity", "Error en guardar item en la web: " + e.getMessage(), e);
				} 
				
				h.post(new Runnable() {
					
					@Override
					public void run() {
						dialog.dismiss();
						Toast.makeText(context, "Item guardado!!", Toast.LENGTH_SHORT).show();
						GastosManager manager = GastosManager.getInstance(context);
						if(manager.isFirstTime()){
							Log.d("AddItemActivity", "Es FirstTime !!");
							manager.setFirstTime(false);
							scheduleFirstTime();
						}
						clearFields();
						Log.d("AddItemActivity", "Se ha agregado un nuevo item en web");
					}
				});
			};
		};
		t.start();
	}
	
	private void scheduleFirstTime(){
		// get a Calendar object with current time
		Calendar cal = Calendar.getInstance();
//		cal.add(Calendar.DAY_OF_MONTH, 1);
		cal.add(Calendar.MINUTE, 3);
		Intent intent = new Intent(getApplicationContext(), GastosReceiver.class);
		intent.putExtra(Constants.EXTRA_ALARM_MESSAGE, Constants.EXTRA_ALARM_MESSAGE_ACTION);

		PendingIntent sender = PendingIntent.getBroadcast(this, Constants.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

		// Get the AlarmManager service
		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
		Log.d(TAG, "Alarma iniciada");
	}
	
	private void clearFields(){
		cantidadCuota.setText("");
		detalle.setText("");
		valorCuota.setText("");
		fechaCompra.setText("");
	}

	private void fill() {
		cantidadCuota.setText("12");
		detalle.setText("LCD");
		valorCuota.setText("120");
		fechaCompra.setText("12-12-11");
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
			 Intent i = new Intent(this, MainActivity.class);
			 startActivity(i);
			 finish();
	    }
	    return super.onKeyDown(keyCode, event);
	}
}
